#include "hal-uart.h"

#include "serial_reg.h"

int hal_uart_tx_available(struct hal_uart *uart)
{
    return (uart->lsr & UART_LSR_THRE) != 0;
}

int hal_uart_putc(struct hal_uart *uart, uint8_t c)
{
    uart->trhr = c;

    return 1;
}

void hal_uart_rxie_set(struct hal_uart *uart, int enable)
{
    if (enable)
    {
        uart->ier |= UART_IER_RDI;
    }
    else
    {
        uart->ier &= ~UART_IER_RDI;
    }
}

void hal_uart_txie_complete_setup(struct hal_uart *uart, int enable)
{
    if (enable)
    {
        uart->ier |= UART_IER_THRI;
    }
    else
    {
        uart->ier &= ~UART_IER_THRI;
    }
}

void hal_uart_reset(struct hal_uart *uart)
{
    uart->ier = UART_IER_UUE;
    uart->fcr = UART_FCR_ENABLE_FIFO | UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT;
    uart->lcr = UART_LCR_WLEN8;
    uart->lsr = 0;
}

int hal_uart_getc(struct hal_uart *uart, uint8_t *c)
{
    if (uart->lsr & UART_LSR_DR)
    {
        *c = uart->trhr;
        return 1;
    }

    return 0;
}

bool hal_uart_status_tx_complete(struct hal_uart *uart)
{
    return (uart->lsr & UART_LSR_THRE) && (uart->ier & UART_IER_THRI);
}
